import os
import queue
import random
import shutil
import threading
import pandas as pd
import time
import traceback  # 添加在文件顶部
from DrissionPage import Chromium, ChromiumOptions, SessionOptions
from DrissionPage.common import Settings
from email_permission import email_list
from DataRecorder import Recorder
from DrissionPage.errors import ElementNotFoundError
from handle_asset_link import collect_direct_link_list_exists

from read_search_file import get_complete_sheet1, mock_click_js
from loguru import logger
from datetime import datetime

lock = threading.Lock()
Settings.set_language("zh_cn")
co = ChromiumOptions(read_file=False)  # 不读取文件方式新建配置对象
so = SessionOptions(read_file=False)
browser = Chromium(addr_or_opts=co, session_options=so)

def log_message(log_callback, message, color=None):
    if callable(log_callback):
        log_callback(message, color) if color else log_callback(message)


def is_number(value):
    return type(value) in (int, float, complex)

def start_sub_account_url(file_path, account_id, log_callback=None):
    df_sheet = get_complete_sheet1(file_path)

    if '创作者ID' not in df_sheet.columns:
        log_message(log_callback, f"表格中缺少创作者ID列", "red")
        return
    if '笔记ID' not in df_sheet.columns:
        log_message(log_callback, f"表格中缺少笔记ID列", "red")
        return
    if 'SPUID' not in df_sheet.columns:
        log_message(log_callback, f"表格中缺少SPUID列", "red")
        return
    # 打开合作伙伴平台页面
    account_tab = browser.new_tab('https://partner.xiaohongshu.com/partner/subAccount-list')

    # TODO 加一个校验步骤， 不是叁柒的所属邮箱直接驳回
    account_tab.ele('tag:span@@class=d-text --color-static --color-text-paragraph --size-text-paragraph text label@@text()^登陆邮箱：').next().child().next().click(by_js=True)
    account_tab.wait(0.5)
    email_str = account_tab.ele('tag:span@@class=d-text --color-static --color-text-paragraph --size-text-paragraph text label@@text()^登陆邮箱：').next().child().text
    email_permission_list = email_list(log_callback)
    if email_str not in email_permission_list:
        log_message(log_callback, f"当前邮箱账号:【{email_str}】暂无权限使用", "red")
        return

    account_tab.ele('tag:input@@class=el-input__inner@@type=text@@autocomplete=off@@placeholder=请输入').click()
    account_tab.ele('tag:input@@class=el-input__inner@@type=text@@autocomplete=off@@placeholder=请输入').input(account_id)
    account_tab.ele('tag:button@@id=search-btn--1').click(by_js=True)

    account_tab.wait(2)

    search_none_ele = account_tab.ele('tag:tr@@class=d-table__empty-row@@text()=暂无数据', timeout=0.5)
    if search_none_ele:
        log_message(log_callback, f"合作伙伴平台子账号ID:{account_id}搜索结果为空, 检查表格第一行子账号ID, 或者检查是否登录合作伙伴平台", "red")
        return

    account_tab.ele('tag:span@@text():跳转', timeout=2).hover()
    jg_ele = account_tab.ele('tag:span@@class=d-text --color-static --color-current --size-text-paragraph d-text-nowrap d-text-ellipsis@@text():聚光平台', timeout=2)

    if jg_ele:
        create_plan_tab = jg_ele.click.for_new_tab(by_js=True)
        create_plan_tab.wait.title_change("计划列表")

        if not df_sheet.empty:
            log_message(log_callback, f'正在执行笔记绑定SPU操作，请勿关闭程序..', "purple")
            unit_dict_cookie = create_plan_tab.cookies(all_info=False).as_dict()

            for index, dd in enumerate(df_sheet.itertuples()):
                bindSpuList = []
                note_id = dd.笔记ID.strip() if pd.notna(dd.笔记ID) else ''
                spu_id = str(dd.SPUID).strip() if pd.notna(dd.SPUID) else ''
                brand_user_id = dd.创作者ID.strip() if pd.notna(dd.创作者ID) else ''

                spu_id_list = spu_id.split("\n")
                for spu_item in spu_id_list:

                    bindSpuList.append({
                        "spuId": spu_item,
                        "spuType": 1
                    })

                data_config = {
                    "elementIds": [note_id],
                    "elementType": 1,
                    "bizSource": 1,
                    "bindSpuList": bindSpuList,
                    "brandUserId": brand_user_id
                }
                log_message(log_callback, f'正在绑定第【{index+1}】条数据 - SPU:{",".join(spu_id_list)} 到笔记:{note_id}..', "purple")
                collect_direct_link_list_exists(cookies=unit_dict_cookie, account_id=account_id, data=data_config, log_callback=log_callback, note_id=note_id, spu_id_list=spu_id_list)

                time.sleep(random.randint(1, 3))
            log_message(log_callback, f'全部数据处理完毕', "green")

# if __name__ == '__main__':
#     file_path = r"../shared/唤端-创建计划-样例.xlsx"
#
#     browser = Chromium()  ## 临时测试、到时候删掉， 只保留调用create_unit()函数
#     unit_view_tab = browser.latest_tab  ## 临时测试、到时候删掉
#     unit_view_tab.get('https://ad.xiaohongshu.com/aurora/ad/create/campaign/4?isStep=true&AFormGrayFlag=false&vSellerId=67403ef0c2f45c001519af4b')  ## 临时测试、到时候删掉
#
#     sheet1_data = get_complete_sheet1(file_path)
#     for index, row in sheet1_data.iterrows():
#         if index == 0:
#             create_plan(unit_view_tab, row, file_path, df_sheet=sheet1_data)















